package com.zmx.piglearn.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.zmx.piglearn.R
import com.zmx.piglearn.model.App
import com.zmx.piglearn.model.Book

class MultiLayoutAdapter (private val dataset: MutableList<Any>, private val context: Context): BaseAdapter() {
    private val TYPE_BOOK = 0
    private val TYPE_APP = 1

    class AppViewHolder (val imgIcon: ImageView, val txtName: TextView)
    class BookViewHolder (val txtName: TextView, val txtAuthor: TextView)

    override fun getCount() = dataset.size

    override fun getItem(p0: Int) = dataset[p0]

    override fun getItemId(p0: Int) = p0.toLong()

    override fun getItemViewType(position: Int): Int {
        if (getItem(position) is App) return TYPE_APP
        if (getItem(position) is Book) return TYPE_BOOK
        return super.getItemViewType(position)
    }

    override fun getViewTypeCount() = 2

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val type = getItemViewType(position)
        val obj = getItem(position)
        val view: View
        if (type == TYPE_APP) {
            view = convertView ?: LayoutInflater.from(context).inflate(R.layout.app_list, parent, false)
            val appHolder: AppViewHolder
            if (convertView == null) {
                appHolder = AppViewHolder(view.findViewById(R.id.img_icon), view.findViewById(R.id.txt_content))
                view.setTag(R.id.tag_app, appHolder)
            } else {
                appHolder = view.getTag(R.id.tag_app) as AppViewHolder
            }
            val app = obj as App
            appHolder.imgIcon.setImageResource(app.imgId)
            appHolder.txtName.text = app.name
        } else { // TYPE_BOOK
            view = convertView ?: LayoutInflater.from(context).inflate(R.layout.book_list, parent, false)
            val bookHolder: BookViewHolder
            if (convertView == null) {
                bookHolder = BookViewHolder(view.findViewById(R.id.txt_title), view.findViewById(R.id.txt_author))
                view.setTag(R.id.tag_book, bookHolder)
            } else {
                bookHolder = view.getTag(R.id.tag_book) as BookViewHolder
            }
            val book = obj as Book
            bookHolder.txtName.text = book.title
            bookHolder.txtAuthor.text = book.author
        }
        return view
    }
}